import React, { Suspense, useEffect, Fragment } from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import { Card } from 'antd';
import ErrorBoundary from '@/util/errorBoundary';


// 加一层错误边界,防止页面整体崩溃
const wrapperComponent = Component => props => {
  return (
    <ErrorBoundary>
      <Suspense fallback={<LoadingPage />}>
        <Component {...props} />
      </Suspense>
    </ErrorBoundary>
  );
};

export default function renderRoutes(routes, extraProps = {}, switchProps = {}) {
  if (!Array.isArray(routes)) {
    return null;
  }
  return (
    <Switch {...switchProps}>
      {routes.map((route, i) => {
        if (route.redirect) {
          return (
            <Redirect
              key={route.key || i}
              from={route.path}
              to={route.redirect}
              exact={route.exact}
              strict={route.strict}
            />
          );
        }
        return (
          <Route
            key={route.key || i}
            path={route.path}
            exact={route.exact}
            strict={route.strict}
            render={props => {
              const childRoutes = renderRoutes(
                route.routes,
                { ...extraProps },
                {
                  location: props.location,
                },
              );

              if (route.component) {
                const Component = wrapperComponent(route.component);

                const content = (
                  <Component {...props} {...extraProps} route={route}>
                    {childRoutes}
                  </Component>
                );

                if (route.path === '/') {
                  return content;
                }

                return route.layout === false ? (
                  <div style={{ margin: 20 }}>{content}</div>
                ) : (
                  <Card
                    style={{ margin: 20, borderRadius: 3 }}
                    bodyStyle={{ padding: 0, backgroundColor: '#f0f2f5' }}
                    bordered={false}>
                    {content}
                  </Card>
                );
              }

              return childRoutes;
            }}
          />
        );
      })}
      <Redirect from="*" to="/404" />
    </Switch>
  );
}